package org.lh.ibernate.core.impl;

import org.lh.ibernate.annotation.Column;
import org.lh.ibernate.core.IFieldHandle;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class FieldHandle implements IFieldHandle {


    //获取所有含有@column注解的字段名称
    @Override
    public List<String> getFieldNameHasColumnAnnotation(Object obj) {
        Class clazz=obj.getClass();
        Field field[]=clazz.getDeclaredFields();
        List<String> fieldNameList=new ArrayList<String>();
        for(Field fieldItem:field){
            fieldItem.setAccessible(true);
            if(fieldItem.isAnnotationPresent(Column.class)){
                Column column=fieldItem.getAnnotation(Column.class);
                String columnName=column.value();
                fieldNameList.add(columnName);
            }
        }
        return fieldNameList;
    }

    //获取所有含有@column注解的字段的属性值
    @Override
    public List<Object> getAttrFromFieldHasColumnAnnotation(Object obj) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class clazz=obj.getClass();
        Field field[]=clazz.getDeclaredFields();
        List<Object> fieldValueList=new ArrayList<Object>();
        for(Field fieldItem:field){
            fieldItem.setAccessible(true);
            if(fieldItem.isAnnotationPresent(Column.class)){
                String fieldName=fieldItem.getName();
                String getMethodName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
                Method method=clazz.getMethod(getMethodName);
                Object value=method.invoke(obj);
                if(value!=null){
                    fieldValueList.add(value);
                }else{
                    fieldValueList.add(null);
                }
            }
        }
        return fieldValueList;
    }
}
